//
//  DLSettingVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/26.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLSettingVC.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "DLSettingTC.h"
#import "DLSettingModel.h"
#import "DLModifyPasswordVC.h"
#import "DLGesPasswordVC.h"

@interface DLSettingVC ()

@property (nonatomic, strong) NSMutableArray *settingDataSource;

@end

@implementation DLSettingVC

- (void) backPreviousPage {
    kuserManager.isRequestUserInfo = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        kuserManager.isRequestUserInfo = YES;
    });
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"viewDidLoad");
    
    [self initDataSource];
    
    [self layoutSubControls];
}
- (void) setUpNav {
    
    self.titleView.title = @"设置";
}
- (void) layoutSubControls {
    
    self.view.backgroundColor = kDLViewNormalBgColor;
    
    self.plainTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenSafeAreaHeight - kHeightNavigation);
    self.plainTableView.backgroundColor = kDLViewNormalBgColor;
    self.plainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.plainTableView.scrollEnabled = NO;
    [self.view addSubview:self.plainTableView];
    
    self.plainTableView.tableHeaderView = [UIView new];
    self.plainTableView.tableFooterView = [UIView new];
    [self.plainTableView registerClass:[DLSettingTC class] forCellReuseIdentifier:@"DLSettingTC"];
    
    UIButton *exitButton = [UIButton buttonWithType:0];
    exitButton.frame = CGRectMake((kScreenWidth - kAutoWidth(313)) / 2, kScreenSafeAreaHeight - kHeightNavigation - 60, kAutoWidth(313), 40);
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    exitButton.titleLabel.font = kSystemFont(17);
    exitButton.backgroundColor = kDLBtnNormalBgColor;
    exitButton.layer.cornerRadius = 3;
    exitButton.clipsToBounds = YES;
    exitButton.layer.borderWidth = 0.5;
    exitButton.layer.borderColor = kColorRGB(30, 145, 250).CGColor;
    [self.view addSubview:exitButton];
    [exitButton addTarget:self action:@selector(exitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void) exitButtonClick {
    NSLog(@"退出登录");
    [kuserManager userLogout];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSArray *arr = self.settingDataSource[section];
    return arr.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 74;
    }
    return 58;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [UIView new];
    footerView.backgroundColor = kDLViewNormalBgColor;
    return footerView;
}
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0.001;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DLSettingTC *settingTC = [tableView dequeueReusableCellWithIdentifier:@"DLSettingTC"];
    
    settingTC.switchBlock = ^(UISwitch * _Nonnull pswSwitch) {
        
        if (indexPath.row == 1) {
            //指纹密码
            if (pswSwitch.isOn) {
                
                [self verifyLocalAuthentication:pswSwitch];
            }
        }
        
        if (indexPath.row == 2) {
            //手势密码
            if (pswSwitch.isOn) {
                DLGesPasswordVC *gpvc = [DLGesPasswordVC new];
                [self.navigationController pushViewController:gpvc animated:YES];
            }
        }
    };
    
    NSArray *arr = self.settingDataSource[indexPath.section];
    DLSettingModel *model = arr[indexPath.row];
    
    settingTC.settingModel = model;
    
    return settingTC;
}
- (void) verifyLocalAuthentication:(UISwitch *)switchControl {
    
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    NSString *reasonStr = @"请使用指纹来认证您的身份";
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        //支持指纹识别
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reasonStr reply:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                //指纹识别成功
                NSLog(@"识别成功");
            } else {
                //指纹识别失败
                // -1: 连续三次指纹识别错误
                // -2: 在TouchID对话框中点击了取消按钮
                // -3: 在TouchID对话框中点击了输入密码按钮
                // -4: TouchID对话框被系统取消，例如按下Home或者电源键
                // -8: 连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
                // -7: 没有添加指纹（待验证）
                NSLog(@"错误码：%zd",error.code);
                NSLog(@"错误信息：%@",error);
            }
        }];
    } else {
        NSLog(@"TouchID设备不可用");
        NSLog(@"错误码：%zd",error.code);
        NSLog(@"错误信息：%@",error);
        switchControl.on = NO;
    }
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *arr = self.settingDataSource[indexPath.section];
    DLSettingModel *model = arr[indexPath.row];
    if (indexPath.section == 0) {
        
    } else if (indexPath.section == 1) {
        if ([model.leftTitle isEqualToString:@"修改登录密码"]) {
            DLModifyPasswordVC *mpvc = [DLModifyPasswordVC new];
            [self.navigationController pushViewController:mpvc animated:YES];
        } else if ([model.leftTitle isEqualToString:@"指纹识别"]) {
            
        } else if ([model.leftTitle isEqualToString:@"手势密码"]) {
            
        } else if ([model.leftTitle isEqualToString:@"风险等级测评"]) {
            
        } else if ([model.leftTitle isEqualToString:@"关于我们"]) {
            
        } else if ([model.leftTitle isEqualToString:@"分享给好友"]) {
            
        }
    }
}
- (void) initDataSource {
    self.settingDataSource = [NSMutableArray array];
    
    
    DLSettingModel *iconCellModel = [DLSettingModel new];
    iconCellModel.isIconCell = YES;
    NSArray *nameInfoArr = @[iconCellModel];
    
    
    NSArray *otherInfoArr = @[@"修改登录密码", @"指纹识别", @"手势密码", @"风险等级测评", @"关于我们", @"分享给好友"];
    NSMutableArray *mutArr = [NSMutableArray array];
    for (NSInteger i = 0; i < otherInfoArr.count; i++) {
        NSString *titleStr = otherInfoArr[i];
        DLSettingModel *model = [DLSettingModel new];
        model.isIconCell = NO;
        model.leftTitle = titleStr;
        
        if ([titleStr isEqualToString:@"风险等级测评"]) {
            model.subTitle = @"稳健型";
        }
        
        if ([titleStr isEqualToString:@"关于我们"]) {
            model.subTitle = @"v1.1.1";
        }
        
        if ([titleStr isEqualToString:@"指纹识别"] || [titleStr isEqualToString:@"手势密码"]) {
            model.isDifferentCell = YES;
        }
        
        [mutArr addObject:model];
    }
    
    [self.settingDataSource addObject:nameInfoArr];
    [self.settingDataSource addObject:mutArr];
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
